package com.xxx.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.RadioGroup;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ViewPager banner;
    private RadioGroup banner_item;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        banner = findViewById(R.id.banner);
        banner.setAdapter(new pager(this));
        banner.setCurrentItem(Integer.MAX_VALUE / 2);
        banner_item = findViewById(R.id.banner_item);
        banner.setOffscreenPageLimit(5);
        banner.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                for (int i = 0; i < 3; i++) {
                    if (i == position % 3) {
                        banner_item.getChildAt(i).setBackgroundResource(R.drawable.yuan2);
                    } else {
                        banner_item.getChildAt(i).setBackgroundResource(R.drawable.yuan);
                    }
                }
            }
        });

        /**
         * 自动轮播
         * */
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                banner.setCurrentItem(banner.getCurrentItem() + 1);
                handler.postDelayed(this::run, 5000);
            }
        }, 2000);

        findViewById(R.id.banner_item0).setOnClickListener(this);
        findViewById(R.id.banner_item1).setOnClickListener(this);
        findViewById(R.id.banner_item2).setOnClickListener(this);

    }


    /**
     * 指示标志
     * */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.banner_item0:
                if (banner.getCurrentItem() % 3 == 2)
                    banner.setCurrentItem(banner.getCurrentItem() + 1);
                else if (banner.getCurrentItem() % 3 == 1)
                    banner.setCurrentItem(banner.getCurrentItem() + 2);
                break;

            case R.id.banner_item1:
                if (banner.getCurrentItem() % 3 == 2)
                    banner.setCurrentItem(banner.getCurrentItem() + 2);
                else
                    banner.setCurrentItem(banner.getCurrentItem() + 1);
                break;
            case R.id.banner_item2:
                if (banner.getCurrentItem() % 3 == 1)
                    banner.setCurrentItem(banner.getCurrentItem() + 1);
                else
                    banner.setCurrentItem(banner.getCurrentItem() + 2);
                break;
        }
    }
}